/**
 * Copyright Notice ====================================================
 * This file contains proprietary information of JeeStrap Co.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2014 All rights reserved. =============================
 */
package com.jeestrap.common.smartcoder.util;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * FreeMarkers工具类
 * 
 * @author JeeStrap
 * @version 2014-01-19
 */
public class FreeMarkers {

	public static String renderString(String templateString, Map<String, ?> model) throws Exception {
		try {
			StringWriter result = new StringWriter();
			Template t = new Template("name", new StringReader(templateString), new Configuration());
			t.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw e;
		}
	}

	public static String renderTemplate(Template template, Object model) throws Exception {
		try {
			StringWriter result = new StringWriter();
			template.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw e;
		}
	}

	public static Configuration buildConfiguration(String directory) throws IOException {
		Configuration cfg = new Configuration();
		String path = FreeMarkers.class.getResource(directory).getFile();
		cfg.setDirectoryForTemplateLoading(new File(path));
		return cfg;
	}
}
